package by.grsu.bso.beans;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import by.grsu.bso.model.Category;
import by.grsu.bso.service.ServiceManager;

public class CategoryUtilBean {

	public CategoryUtilBean() {
		
	}
	
	public Category getParentCategory(String catId) {
		
		Category current = getCategory(catId);
		if(current!=null) {
			int parentId = current.getParentCategoryId();
			return getCategory(Integer.toString(parentId));
		}
		
		return null;
	}
	
	
	public Category getCategory(String catId){
		
		Integer categoryID = null;
		
		try{
			categoryID = Integer.parseInt(catId);
		} catch (Exception e) {			
		}
		
		if (categoryID == null)
			return null;
		
		try{
			return ServiceManager.getCategoryService().findById(categoryID);
		}catch(Exception e){
			
		}
		
		return null;
	}
	
	public List<Category> getCategories() { 
		return getCategories("1");
	}
	
	public List<Category> getCategories(String parent) {
		
		int parentCategory = 1;
		
		try{
			parentCategory = Integer.parseInt(parent);
		} catch (Exception e) {			
		}
		
		List<Category> result = new ArrayList<Category>();
		
		try {
			List<Category> found = ServiceManager.getCategoryService().findByParent(parentCategory);
			
			if (found != null) {
				result.addAll(found);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return result; 
	}

}
